<?php

if (!defined('BASEPATH'))
    exit('Vui lòng liên hệ nhatnv');

class MY_Controller extends CI_Controller {

    public $_data;
    
    public $app_id = '563383537078971';
    public $app_secret = '15d6d14b8f57b05e73e76550c3bdc30a';
    
    public function __construct() {
        parent::__construct();
        
        $this->load->helper(array('url', 'text', 'form'));
        $this->load->library('session');

        $this->data['id_mem'] = $this->session->userdata('id_mem') ? $this->session->userdata('id_mem') : 0;
        $this->data['baseurl'] = site_url();
        $this->data['imgurl'] = 'http://125.212.192.114/VTVDEV/data/';
        $this->data['baseapi'] = 'http://125.212.192.114/VTVDEV/api/';
        $this->data['socketNode'] = 'http://125.212.192.114/VTVDEV/';
        $this->data['linkExport'] = 'http://export.babybean.vn/exportexcel.php';
        $this->data['fview'] = new Ultility;

        $this->data['list_tvshow'] = $this->get_list_tvshow();
		$this->data['list_qrcode'] = $this->list_qrcode();
    }

    public function createguest() {
        if (in_array($this->data['id_mem'], array(null, '', '0'))) {
            //create account info default
            $this->data['acc_default'] = array(
                'id_mem' => time() . rand(100, 999),
                'username_mem' => '',
                'fullname_mem' => '',
                'avatar' => '',
                'role' => 'guest',
                'point' => '',
                'email' => '',
                'address' => '',
                'mobile' => '',
                'birthday' => '',
                'flag' => -1
            );
            $this->session->set_userdata($this->data['acc_default']);
        }
    }

    public function get_list_tvshow() {
        $flag = $this->db->query("SELECT flag FROM flag LIMIT 1")->row_object()->flag;
        //die($flag.'a');
        if(@$this->session->userdata('flag') != $flag){
            $sql = "SELECT tv.*,c.logo FROM tvshow AS tv LEFT JOIN channel AS c ON tv.channel_id = c.id ORDER BY tv.id DESC";
            $data = $this->db->query($sql)->result_array();
            $result = array();
            //die($this->session->userdata('id_mem'));
            if (!in_array($this->session->userdata('id_mem'), array(null, '')) && $this->session->userdata('role') == "member") {
                foreach ($data AS $key => $value) {
                    $count = $this->db->query("SELECT id FROM follow_tvshow WHERE user_id = " . $this->session->userdata('id_mem') . " AND tvshow_id = " . $value['id'])->num_rows();
                    if ($count == 1) {
                        $value['follow'] = 1;
                    } else {
                        $value['follow'] = 0;
                    }
                    $result[] = $value;
                }
                $sess = array(
                    'data' => $result,
                    'flag' => $flag
                );
                $this->session->set_userdata($sess);
                return $result;
            } else {
                foreach ($data AS $key => $value) {
                    $value['follow'] = 1;
                    $result[] = $value;
                }
                $sess = array(
                    'data' => $result,
                    'flag' => $flag
                );
                $this->session->set_userdata($sess);
                return $result;
            }
        }else{
            return $this->session->userdata('data');
        }
    }
	
	public function list_qrcode(){
		return $this->db->query('SELECT * FROM version_app_os ')->row_array();
	}
	
	
    public function rplUriCtl($var) {
        $vowels = array("-", " -", "- ", "“", "”", "   ", "  ", "    ", " ", "/", '\"', "\'", "+", "=", "{", "}", ")", "(", "!", "`", "'", "~", "@", "#", "$", "%", "^", "&", "*", "_", "!", "!", ".", ",", ";", ":", "]", "[", "/");
        $rc = strtolower(str_replace($vowels, '-', rtrim(ltrim(str_replace(array('?', 'quot'), '', $var)))));
        return preg_replace('/--+/', '-', $rc);
    }

    public function checkUser($id) {
        if (in_array($id, array(null, '', '0'))) {
            redirect('dang-nhap');
        }
        $db = $this->db->query('SELECT id FROM user WHERE id = ' . $id . '')->num_rows();
        if ($db == 0) {
            redirect('dang-nhap');
        }
    }

    public function checkAdmin($id) {
        // echo $id.'----'; die();
        if (in_array($id, array(null, '', '0'))) {
            redirect('manage/login');
        }
        $db = $this->db->query('SELECT id FROM user WHERE id = ' . $id . ' AND manager = 1')->num_rows();
        if ($db == 0) {
            redirect('manage/login');
        }
    }

    public function get_ascii($st) {

        $vietChar = 'á|à|ả|ã|ạ|ă|ắ|ằ|ẳ|ẵ|ặ|â|ấ|ầ|ẩ|ẫ|ậ|é|è|ẻ|ẽ|ẹ|ê|ế|ề|ể|ễ|ệ|ó|ò|ỏ|õ|ọ|ơ|ớ|ờ|ở|ỡ|ợ|ô|ố|ồ|ổ|ỗ|ộ|ú|ù|ủ|ũ|ụ|ư|ứ|ừ|ử|ữ|ự|í|ì|ỉ|ĩ|ị|ý|ỳ|ỷ|ỹ|ỵ|đ|Á|À|Ả|Ã|Ạ|Ă|Ắ|Ằ|Ẳ|Ẵ|Ặ|Â|Ấ|Ầ|Ẩ|Ẫ|Ậ|É|È|Ẻ|Ẽ|Ẹ|Ê|Ế|Ề|Ể|Ễ|Ệ|Ó|Ò|Ỏ|Õ|Ọ|Ơ|Ớ|Ờ|Ở|Ỡ|Ợ|Ô|Ố|Ồ|Ổ|Ỗ|Ộ|Ú|Ù|Ủ|Ũ|Ụ|Ư|Ứ|Ừ|Ử|Ữ|Ự|Í|Ì|Ỉ|Ĩ|Ị|Ý|Ỳ|Ỷ|Ỹ|Ỵ|Đ';
        $engChar = 'a|a|a|a|a|a|a|a|a|a|a|a|a|a|a|a|a|e|e|e|e|e|e|e|e|e|e|e|o|o|o|o|o|o|o|o|o|o|o|o|o|o|o|o|o|u|u|u|u|u|u|u|u|u|u|u|i|i|i|i|i|y|y|y|y|y|d|A|A|A|A|A|A|A|A|A|A|A|A|A|A|A|A|A|E|E|E|E|E|E|E|E|E|E|E|O|O|O|O|O|O|O|O|O|O|O|O|O|O|O|O|O|U|U|U|U|U|U|U|U|U|U|U|I|I|I|I|I|Y|Y|Y|Y|Y|D';

        $arrVietChar = explode("|", $vietChar);
        $arrEngChar = explode("|", $engChar);
        $ftc = strtolower(str_replace($arrVietChar, $arrEngChar, (string) $st));
        $ftc_ = str_replace($arrVietChar, $arrEngChar, $ftc);
        $vowels = array("-", " -", "- ", " ", "/", "+", "=", "{", "}", ")", "(", "!", "`", "'", "~", "@", "#", "$", "%", "^", "&", "*", "_", "!", "!", ".", ",", ";", ":", "]", "[", "/");
        $dtr = str_replace($vowels, ' ', $ftc_);

        $vowels_ = array('\"');
        return $this->get_slug(str_replace($vowels_, ' ', $dtr));
    }

    private function get_slug($st) {
        $Char = '̀|̣|̉|́|̃|:|.|,|?|!|"|&quot;|;|{|}|(|)|《 | 》|《|》';
        $explChar = explode("|", $Char);
        return strtolower(str_replace($explChar, '', $st));
    }

    public function get_ascii_upload($st) {
        $vietChar = 'á|à|ả|ã|ạ|ă|ắ|ằ|ẳ|ẵ|ặ|â|ấ|ầ|ẩ|ẫ|ậ|é|è|ẻ|ẽ|ẹ|ê|ế|ề|ể|ễ|ệ|ó|ò|ỏ|õ|ọ|ơ|ớ|ờ|ở|ỡ|ợ|ô|ố|ồ|ổ|ỗ|ộ|ú|ù|ủ|ũ|ụ|ư|ứ|ừ|ử|ữ|ự|í|ì|ỉ|ĩ|ị|ý|ỳ|ỷ|ỹ|ỵ|đ|Á|À|Ả|Ã|Ạ|Ă|Ắ|Ằ|Ẳ|Ẵ|Ặ|Â|Ấ|Ầ|Ẩ|Ẫ|Ậ|É|È|Ẻ|Ẽ|Ẹ|Ê|Ế|Ề|Ể|Ễ|Ệ|Ó|Ò|Ỏ|Õ|Ọ|Ơ|Ớ|Ờ|Ở|Ỡ|Ợ|Ô|Ố|Ồ|Ổ|Ỗ|Ộ|Ú|Ù|Ủ|Ũ|Ụ|Ư|Ứ|Ừ|Ử|Ữ|Ự|Í|Ì|Ỉ|Ĩ|Ị|Ý|Ỳ|Ỷ|Ỹ|Ỵ|Đ';
        $engChar = 'a|a|a|a|a|a|a|a|a|a|a|a|a|a|a|a|a|e|e|e|e|e|e|e|e|e|e|e|o|o|o|o|o|o|o|o|o|o|o|o|o|o|o|o|o|u|u|u|u|u|u|u|u|u|u|u|i|i|i|i|i|y|y|y|y|y|d|A|A|A|A|A|A|A|A|A|A|A|A|A|A|A|A|A|E|E|E|E|E|E|E|E|E|E|E|O|O|O|O|O|O|O|O|O|O|O|O|O|O|O|O|O|U|U|U|U|U|U|U|U|U|U|U|I|I|I|I|I|Y|Y|Y|Y|Y|D';
        $arrVietChar = explode("|", $vietChar);
        $arrEngChar = explode("|", $engChar);
        $ftc = strtolower(str_replace($arrVietChar, $arrEngChar, $st));
        $vowels = array("-", " -", "- ", "“", "”", "   ", "  ", "    ", " ", "/", '\"', "\'", "+", "=", "{", "}", ")", "(", "!", "`", "'", "~", "@", "#", "$", "%", "^", "&", "*", "_", "!", "!", ".", ",", ";", ":", "]", "[", "/");
        return str_replace($vowels, '-', $ftc);
    }

    public function savefile($base64_string, $paths, $nameimagess, $url_convert = 'd') {
        @mkdir($paths, 0301);
        $ifp = fopen($paths . $nameimagess, "wb");
        fwrite($ifp, base64_decode($base64_string));
        fclose($ifp);
        return $this->downloadPicture($paths, $this->data['baseurl'], $url_convert, $nameimagess);
        //return 
    }

    private function downloadPicture($imagesource, $base, $url_convert, $nameimagess) {
        $img_src = $imagesource . 'tmp/' . $nameimagess;
        list($width, $height) = @getimagesize($img_src);
        $new_width = $width;
        $new_height = $height;
        if (in_array(@$width, array(null, '', '0')) || in_array(@$height, array(null, '', '0'))) {
            @unlink($imagesource . 'tmp/' . $nameimagess);
            return '201';
        }
        @$image_p = imagecreatetruecolor($new_width, $new_height);
        @$image = imagecreatefromjpeg($img_src);
        @imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
        @imagejpeg($image_p, $imagesource . $nameimagess, 100);
        @unlink($imagesource . 'tmp/' . $nameimagess);
        @imagedestroy($image);
        return '200';
    }

    public function printstr($str, $len) {
        $arrstr = explode(" ", $str);
        $detail = "";
        $return = "";
        if (count($arrstr) <= $len)
            $len = count($arrstr);
        else {
            $detail = " ...";
        }
        for ($i = 0; $i < $len; $i++) {
            $return .= $arrstr[$i] . " ";
        }

        return $return . '...';
    }

    public function saveSession($array = '') {
        if (!in_array($array, array(null, '', '0'))) {
            foreach ($array AS $key => $val) {
                $_SESSION[$key] = $val;
            }
            $_SESSION['auth'] = sha1(md5($_SERVER["REMOTE_ADDR"]) . md5(md5($_SERVER["HTTP_USER_AGENT"])));
        }
        return $array;
    }

    public function rplUri($var) {
        $vowels = array("-", " -", "- ", "“", "”", "   ", "  ", "    ", " ", "/", '\"', "\'", "+", "=", "{", "}", ")", "(", "!", "`", "'", "~", "@", "#", "$", "%", "^", "&", "*", "_", "!", "!", ".", ",", ";", ":", "]", "[", "/");
        $rc = strtolower(str_replace($vowels, '-', rtrim(ltrim(str_replace(array('?', 'quot'), '', $var)))));
        return preg_replace('/--+/', '-', $rc);
    }

    private function str_equal($str) {
        return str_replace('=', '%3D', $str);
    }

    public function getParamStringAdmin($param) {
        return addslashes(isset($_REQUEST[$param]) ? $this->str_equal(quotes_to_entities($_REQUEST[$param])) : '');
    }

    public function getParamString($param) {
        return addslashes(isset($_REQUEST[$param]) ? $this->security->xss_clean($_REQUEST[$param]) : '');
    }

    public function getParamArray($param) {
        return isset($_REQUEST[$param]) ? $this->security->xss_clean($_REQUEST[$param]) : '';
    }

    public function getParamInt($param) {
        return intval(isset($_REQUEST[$param]) ? $this->security->xss_clean($_REQUEST[$param]) : '');
    }

    public function generateCode($n) {
        $n = rand(10e16, 10e20);
        return base_convert($n, 10, 36);
    }

    public function getParamUrl($id) {
        return intval(MY_Controller::decode_id($this->security->xss_clean($this->uri->segment($id))));
    }

    public function getParamUri($id, $param) {
        if ($param == '1') {
            return intval($this->security->xss_clean($this->uri->segment($id)));
        } else if ($param == '3') {
            $param_ = $this->security->xss_clean($this->uri->segment($id));
            if (in_array($param_, array(null, '', '0'))) {
                return 0;
            }
            $data = explode('-', addslashes($param_));
            return $data[1];
        } else {
            return addslashes($this->security->xss_clean($this->uri->segment($id)));
        }
    }

    public function getSslPages($url) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }

    public function getSslPage($url) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_REFERER, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }

    public function encode_id($id) {
        $str = dechex($id + 307843210);
        $str = str_replace("1", "i", $str);
        $str = str_replace("2", "w", $str);
        $str = str_replace("3", "o", $str);
        $str = str_replace("4", "u", $str);
        $str = str_replace("5", "z", $str);
        return $str;
    }

    public function decode_id($str) {
        $str = str_replace("i", "1", $str);
        $str = str_replace("w", "2", $str);
        $str = str_replace("o", "3", $str);
        $str = str_replace("u", "4", $str);
        $str = str_replace("z", "5", $str);
        $str = hexdec($str) - 307843210;
        return $str;
    }

    /// validate ajax
    public function alpha_dash($str) {
        return (!preg_match("/^([-a-z0-9_-])+$/i", $str)) ? 1 : 0;
    }

    public function valid_email($str) {
        return (!preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $str)) ? 1 : 0;
    }

    public function min_length($str, $val) {
        if (preg_match("/[^0-9]/", $val)) {
            return FALSE;
        }

        if (function_exists('mb_strlen')) {
            return (mb_strlen($str) < $val) ? 1 : 0;
        }

        return (strlen($str) < $val) ? 1 : 0;
    }

    public function required($str) {
        if (!is_array($str)) {
            return (trim($str) == '') ? 1 : 0;
        } else {
            return (!empty($str));
        }
    }
    
    public function watermarkImage($SourceFile, $WaterMarkText, $DestinationFile, $font_size, $left = 0, $top = 0, $font) { 
       list($width, $height) = getimagesize($SourceFile);
       $image_p = imagecreatetruecolor($width, $height);
       $image = imagecreatefromjpeg($SourceFile);
       imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width, $height); 
       $black = imagecolorallocate($image_p, 0, 0, 0);
       
       imagettftext($image_p, $font_size, 0, $left, $top, $black, $font, $WaterMarkText);
       if ($DestinationFile<>'') {
          imagejpeg ($image_p, $DestinationFile, 100); 
       } else {
          header('Content-Type: image/jpeg');
          imagejpeg($image_p, null, 100);
       };
       imagedestroy($image); 
       imagedestroy($image_p); 
    }
    
    
    public function addcover($imagesource, $cover, $path, $top, $left)
    {
    	@$filetype = strtolower(substr($imagesource,strlen($imagesource)-4,4));
    	if($filetype == ".gif") $image = @imagecreatefromgif($imagesource);
    	if($filetype == ".jpg") $image = @imagecreatefromjpeg($imagesource);
    	if($filetype == ".png") $image = @imagecreatefrompng($imagesource);
    	$watermark = @imagecreatefromjpeg($cover);
    	$imagewidth = imagesx($image);
    	$imageheight = imagesy($image);
    	$watermarkwidth = imagesx($watermark);
    	$watermarkheight = imagesy($watermark);
    	$sx = $watermarkwidth;
    	$sy = $watermarkheight;
    	imagecopy($image, $watermark, 0, 1, $left, $top, $watermarkwidth, $watermarkheight);
    	@imagejpeg($image,$path,100);
    }

}
